﻿using LaserAutoTest.UI.ViewModels.Mains;
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LaserAutoTest.UI.Views.Mains
{
    /// <summary>
    /// TestView.xaml 的交互逻辑
    /// </summary>
    public partial class TestView : UserControl
    {
        //TestViewModel viewModel = new TestViewModel();
        public TestView()
        {
            InitializeComponent();
            string rootPath = Environment.CurrentDirectory;
            webView.Source = new Uri(rootPath+"\\Test.html");
            webView.EnsureCoreWebView2Async();
            
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            webView.CoreWebView2.PostWebMessageAsString(txtMsg.Text);
            
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //webView.CoreWebView2.ExecuteScriptAsync($"alert('{txtMsg.Text}')");
            webView.CoreWebView2.ExecuteScriptAsync($"Show('{txtMsg.Text}')");
            //webView.CoreWebView2.ExecuteScriptAsync($"ShowMessage()");
        }

        private async void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            await webView.EnsureCoreWebView2Async();

            webView.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
            await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);");
            //CoreWebView2.PostWebMessageAsString 或 CoreWebView2.PostWebMessageAsJson 方法发送消息给 WebView2 控件时，这个事件监听器会被触发
            await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\\'message\\', event => alert(event.data));\"");

            //webView.CoreWebView2.AddHostObjectToScript("view", viewModel);
            ////注册全局变量
            //await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var view = window.chrome.webview.view;");
        }

        private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
           MessageBox.Show(e.TryGetWebMessageAsString());
        }
    }
}
